﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Compression;


namespace Stream
{
    class Program
    {
        static void Main(string[] args)
        {
            TestGZipStream();
        }


        public static void TestGZipStream()
        {
            // gzip 压缩文件 - 往 GzipSteam 写数据
            GZipStream gzs = new GZipStream(new FileStream(@"files\b.gz", FileMode.OpenOrCreate), CompressionMode.Compress);
            FileStream f = new FileStream(@"files\b.pdf", FileMode.Open, FileAccess.Read);

            
            byte[] buffer = new byte[1024];     // FileStream 的 CopyTo 必须 .net 4+ 才支持
            while (f.Read(buffer, 0, buffer.Length) > 0)
            {
                gzs.Write(buffer, 0, buffer.Length);
            }
            gzs.Close();
            f.Close();

            // gzip 解压缩 - 从 GzipStream 读数据
            buffer.Initialize();
            GZipStream deGzs = new GZipStream(new FileStream(@"files\b.gz", FileMode.Open), CompressionMode.Decompress);
            FileStream deF = new FileStream(@"files\b.gz.pdf", FileMode.OpenOrCreate);
            while (deGzs.Read(buffer, 0, buffer.Length) > 0)
            {
                deF.Write(buffer, 0, buffer.Length);
            }
            deGzs.Close();
            deF.Close();
        }

        public static void TestMemoryStream()
        {
           
            /**
             * MemoryStream
             * 
             *      .WriteTo(stream)        将stream的整个内容写入到另一个流
             *      .ToArray()              将stream的整个内容写入字节数组
             *      .CoptyTo(stream)        将stream的整个内容复制到另一个流
             *  
             */


                // 直接使用 MemoryStream 读写字符串
            MemoryStream ms = new MemoryStream();
            String s = "abc";
            byte[] b = Encoding.Default.GetBytes(s);

            ms.Write(b, 0, b.Length);
            ms.Seek(0, SeekOrigin.Begin);
            byte[] r = new byte[b.Length];
            int len = ms.Read(r, 0, b.Length);

            Console.WriteLine("len: {0}, s: {1}", len, Encoding.Default.GetString(r));



            // 使用 StreamWriter StreamReader 读写 MemoryStream
            MemoryStream mem = new MemoryStream();
            StreamWriter sw = new StreamWriter(mem);
            sw.WriteLine("A");
            sw.WriteLine("B");
            sw.Flush();
            Console.WriteLine("stream len：{0}", sw.BaseStream.Length);

            StreamReader sr = new StreamReader(mem);
            sr.BaseStream.Seek(0, SeekOrigin.Begin);
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }



            Console.ReadKey();
        }
    }
}
